using System;
using FBroSharp;
using FBroSharp.Event;
using FBroSharp.Lib;
using FBroSharp.Const;
using FBroSharp.Callback;
using FBroSharp.Value;
using FBroSharp.DataType;

namespace JavaScript对话框自动化处理器
{
    /// <summary>
    /// 浏览器事件处理器 - 包含JavaScript对话框处理
    /// </summary>
    public class BrowserEvent : FBroSharpBrowserEvent
    {
        private readonly JSDialogHandler dialogHandler;

        public BrowserEvent(JSDialogHandler handler)
        {
            dialogHandler = handler;
        }

        /// <summary>
        /// ⚠️ CRITICAL: JavaScript对话框处理（alert、confirm、prompt）
        /// </summary>
        public override bool OnJSDialog(IFBroSharpBrowser browser, string origin_url, FBroJsDialogType dialog_type, 
            string message_text, string default_prompt_text, IFBroSharpJSDialogCallback callback, ref bool suppress_message)
        {
            try
            {
                // 使用对话框处理器处理
                return dialogHandler.HandleDialog(dialog_type, message_text, default_prompt_text, callback);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"JavaScript对话框处理异常: {ex.Message}");
                // 发生异常时默认接受对话框
                callback.Continue(true, default_prompt_text);
                return true;
            }
        }

        /// <summary>
        /// ⚠️ REQUIRED: 浏览器创建完成（TWO parameters!）
        /// </summary>
        public override void OnAfterCreated(IFBroSharpBrowser browser, IFBroSharpDictionaryValue extrainfo)
        {
            Console.WriteLine($"浏览器创建完成，ID：{browser.GetIdentifier()}");
        }

        /// <summary>
        /// 标题变更
        /// </summary>
        public override void OnTitleChange(IFBroSharpBrowser browser, string title)
        {
            Console.WriteLine($"标题变更: {title}");
        }

        /// <summary>
        /// 地址变更
        /// </summary>
        public override void OnAddressChange(IFBroSharpBrowser browser, IFBroSharpFrame frame, string url)
        {
            if (frame.IsMain())
            {
                Console.WriteLine($"URL 变更: {url}");
            }
        }

        /// <summary>
        /// 加载状态变更
        /// </summary>
        public override void OnLoadingStateChange(IFBroSharpBrowser browser, bool isLoading, bool canGoBack, bool canGoForward)
        {
            Console.WriteLine($"加载状态: {(isLoading ? "加载中" : "加载完成")}");
        }

        /// <summary>
        /// 开始加载
        /// </summary>
        public override void OnLoadStart(IFBroSharpBrowser browser, IFBroSharpFrame frame, FBroSharpTransitionType transition_type)
        {
            if (frame.IsMain())
            {
                Console.WriteLine($"[Browser] 开始加载: {frame.GetURL()}");
            }
        }

        /// <summary>
        /// 加载完成
        /// </summary>
        public override void OnLoadEnd(IFBroSharpBrowser browser, IFBroSharpFrame frame, int httpStatusCode)
        {
            if (frame.IsMain())
            {
                Console.WriteLine($"[Browser] 加载完成: {frame.GetURL()} (HTTP {httpStatusCode})");
            }
        }

        /// <summary>
        /// 加载错误
        /// </summary>
        public override void OnLoadError(IFBroSharpBrowser browser, IFBroSharpFrame frame, 
            int errorCode, string errorText, string failedUrl)
        {
            if (frame.IsMain())
            {
                Console.WriteLine($"页面加载错误: {errorText} ({failedUrl})");
            }
        }

        /// <summary>
        /// ⚠️ CRITICAL FOR SINGLE-WINDOW APPS: 阻止弹窗
        /// </summary>
        public override bool OnBeforePopup(IFBroSharpBrowser browser, IFBroSharpFrame frame, string target_url, 
            string target_frame_name, FBroSharpWindowOpenDisposition target_disposition, bool user_gesture, 
            FBroSharpPopupfeatures popupFeatures, ref FBroSharpWindowsInfo windowInfo, 
            ref FBroSharpBrowserSetting settings, ref bool no_javascript_access, IFBroSharpUseExtraData user_settings)
        {
            // 在当前窗口打开链接而不是新窗口
            frame.LoadURL(target_url);
            return true; // true = 阻止弹窗
        }

        /// <summary>
        /// 浏览器即将关闭
        /// </summary>
        public override void OnBeforeClose(IFBroSharpBrowser browser)
        {
            Console.WriteLine("浏览器即将关闭");
        }

        /// <summary>
        /// 是否允许浏览器关闭
        /// </summary>
        public override bool DoClose(IFBroSharpBrowser browser)
        {
            return false; // false = 允许关闭
        }
    }
}

